package cn.itrip.utlis;


import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

public class RedisAPI {
    private JedisPool jedisPool;

    public JedisPool getJedisPool() {
        return jedisPool;
    }
    public void setJedisPool(JedisPool jedisPool) {
        this.jedisPool = jedisPool;
    }

    public String get(String key) {
        Jedis jedis = null;
        try{
            jedis = jedisPool.getResource();
            return jedis.get(key);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            returnResource(jedisPool,jedis);
        }
        return null;
    }
    public boolean set(String key,String value) {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            jedis.set(key,value);
            return true;
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            returnResource(jedisPool,jedis);
        }
        return false;
    }

    public boolean setex(String key,int seconds, String value) {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            jedis.setex(key,seconds,value);
            return true;
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            returnResource(jedisPool,jedis);
        }
        return false;
    }

    public void del(String key) {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            jedis.del(key);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            returnResource(jedisPool,jedis);
        }
    }

    public Long ttl(String key) {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            return jedis.ttl(key);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            returnResource(jedisPool,jedis);
        }
        return -1L;
    }

    public static void returnResource(JedisPool pool,Jedis redis){
        if(redis != null){
            pool.returnResource(redis);
        }
    }
}
